package net.xdclass.job.job;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author whg
 * @create 2023/9/21 15:17
 * @description：
 */
@Component
public class MyJobHandler {

    private static final Logger logger = LoggerFactory.getLogger(MyJobHandler.class);

    @XxlJob(value = "demoJobHandler",init = "init",destroy = "destroy")
    public void execute(){
        String param = XxlJobHelper.getJobParam();
        logger.info("小滴课堂 execute 任务执行成功，请求参数：{}",param);
        if (param.equals("1")){
            XxlJobHelper.log("执行成功，打印日志");
            XxlJobHelper.handleSuccess("执行成功");
        }else {
            //throw new RuntimeException("RuntimeException:执行失败");
            XxlJobHelper.log("执行失败，打印日志");
            XxlJobHelper.handleFail("执行失败");
        }
    }

    /**
     * 分片广播任务
     */
    @XxlJob(value = "shardingJobHandler",init = "init",destroy = "destroy")
    public void shardingJobHandler(){
        //当前分片序号，从0开始，即执行器的序号
        int shardIndex = XxlJobHelper.getShardIndex();
        //总分片数，执行器集群总机器数量
        int shardTotal = XxlJobHelper.getShardTotal();

        XxlJobHelper.log("分片参数：当前分片序号 = {}，总分片数 = {}",
                shardIndex,shardTotal);

        //查询所有待执行的任务
        List<Integer> allUserIds = getAllUserIds();
        //过滤出当前执行器需要执行的任务，并执行
        for (Integer item : allUserIds){
            if (item % shardTotal == shardIndex){
                //执行任务
                logger.info("第{}片，命中分片开始处理用户id={}",shardIndex,item);
            }
        }
    }

    /**
     * 模拟从数据库中取所有的待执行任务
     * @return
     */
    private List<Integer> getAllUserIds(){
        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            ids.add(i);
        }
        return ids;
    }


    private void init(){
        logger.info("小滴课堂 MyJobHandler init >>>>>");
    }

    private void destroy(){
        logger.info("小滴课堂 MyJobHandler destroy >>>>>");
    }
}
